/**
 * 系统管理 用户管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInlinew" class="user-search">
      <el-form-item label="搜索：">
      </el-form-item>
      <el-form-item label="">
        <el-input size="small" v-model="formInlinew.username" placeholder="输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input size="small" v-model="formInlinew.phone" placeholder="输入手机号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" @selection-change="selectChange" :data="userData" highlight-current-row v-loading="loading"
      border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="50">
      </el-table-column>
      <el-table-column align="center" sortable prop="username" label="用户名" width="120">
      </el-table-column>
      <el-table-column align="center" sortable prop="nickname" label="姓名" width="120">
      </el-table-column>
      <el-table-column align="center" sortable prop="phone" label="手机号" width="120">
      </el-table-column>
      <el-table-column align="center" sortable prop="role" label="角色" min-width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.role == 1">微信用户</span>
          <span v-else-if="scope.row.role == 2">体育馆管理员</span>
          <span v-else-if="scope.row.role == 3">系统管理员</span>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="birthday" label="生日" min-width="120">
      </el-table-column>
      <el-table-column align="center" sortable prop="profile" label="头像" min-width="120">
        <template slot-scope="scope"> <img :src="`${imgUrl}${scope.row.profile}`" alt="头像"
            style="width: 80px; height: 80px;"> </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="agreement" label="健康承诺书" min-width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.agreement == 0">×</span>
          <span v-else-if="scope.row.agreement == 1">√</span>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="status" label="实名" min-width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 0">×</span>
          <span v-else-if="scope.row.status == 1">√</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="100" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="80px" ref="editForm" :model="editForm" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input size="small" v-model="editForm.username" auto-complete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="nickname">
          <el-input size="small" v-model="editForm.nickname" auto-complete="off" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input size="small" v-model="editForm.phone" @input="checkPhoneNumber" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select size="small" v-model="editForm.roleId" placeholder="请选择" class="userRole">
            <el-option label="微信用户" value="1"></el-option>
            <el-option label="商家" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker value-format="yyyy-MM-dd" size="small" v-model="editForm.birthday"
            placeholder="请选择生日"></el-date-picker>
        </el-form-item>
        <el-form-item label="头像" prop="profile">
          <el-upload action="http://192.168.1.110:8080/uploadbImage/" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload" list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload> 菜单管理
        </el-form-item>
        <el-form-item label="健康承诺书" prop="agreement">
          <el-select size="small" v-model="editForm.agreement" placeholder="请选择" class="userRole">
            <el-option label="同意" value="1"></el-option>
            <el-option label="拒绝" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实名" prop="status">
          <el-select size="small" v-model="editForm.status" placeholder="请选择" class="userRole">
            <el-option label="同意" value="1"></el-option>
            <el-option label="拒绝" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入请求方法
import store from "../../vuex/store";
import { UTLSTORE } from "../../api/config"
import {
  userList,
  userSave,
  userDelete
} from '../../api/userMG'
import Pagination from '../../components/Pagination';

export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      title: '添加用户',
      editFormVisible: false, //控制编辑页面显示与隐藏
      dataAccessshow: false, //控制数据权限显示与隐藏
      // 编辑与添加
      editForm: {
        id: '',
        username: '',
        password: '',
        nickname: '',
        phone: '',
        role: '',
        status: '',
        registerDate: '',
        profile: '',
        agreement: '',
        birthday: '',
        idcard: '',
        fillname: '',
        token: localStorage.getItem('logintoken')
      },
      // 选择数据
      selectdata: [],
      // rules表单验证
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
            required: true,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ]
      },
      // 删除用户
      seletedata: {
        ids: '',
        token: localStorage.getItem('logintoken')
      },
      // 请求数据参数
      formInlinew: {
        page: 1,
        limit: 10,
        nickname: '',
        phone: '',
        role: '',
        status: '',
        registerDate: '',
        profile: '',
        birthday: '',
        fillname: '',
        idcard: ''
      },
      // 请求数据参数
      formInline: {
        page: 1,
        limit: 10,
        nickname: '',
        phone: '',
        role: '',
        status: '',
        registerDate: '',
        profile: '',
        birthday: '',
        fillname: '',
        idcard: ''
      },
      //用户数据

      // 数据权限
      UserDept: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 选中
      checkmenu: [],
      //参数role
      saveroleId: '',
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    }
  },
  // 注册组件
  components: {
    Pagination
  },

  /**
   * 数据发生改变
   */
  watch: {},
  computed: {
    imgUrl() {
      return UTLSTORE;
    },
    userData() {
      return store.state.userDatatoo
    },

  },

  /**
   * 创建完毕
   */
  created() {
    this.userdatafetch()
    // this.userData=store.state.userDatatoo;

  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    userdatafetch() {
      userList(JSON.stringify(this.formInline)).then(res => {
        console.log(res.data)
        store.commit("setUserDatatoo", res.data)
      }).catch(err => console.log(err))
    },
    handleAvatarSuccess(response, file, fileList) {
      this.editForm.profile = '/images/' + file.name;
      console.log(row.profile.name)
    },
    beforeAvatarUpload(file) {
      console.log("file=====", file)
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('只能上传 JPG 格式的图片！');
      } else if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }

      return isJPG && isLt2M;
    },
    // 获取数据方法
    getdata(parameter) {
      //获取用户列表
      userList(parameter).then(res => {
        console.log(res)
        // console.log(parameter)
        this.loading = false
        if (res.success == false) {
          this.$message({
            type: 'info',
            message: res.msg
          })
        } else {
          this.userData = res.data
          // 分页赋值
          this.pageparm.currentPage = this.formInline.page
          this.pageparm.pageSize = this.formInline.limit
          this.pageparm.total = res.count
        }
      })
    },
    // 编辑、添加提交方法
    submitForm() {
      // console.log(this.editForm)
      // let obj={
      //   user:this.editForm}
      // console.log("++++++",obj)
      // console.log(this.$refs[editData].validate())
      // let editData=this.editForm;
      // this.$refs[editData].validate(valid => {
      //   if (valid) {
      //     console.log("-----------------------")
      //     // 请求方法
      //     userSave(obj)
      //       .then(res => {
      //         this.editFormVisible = false
      //         this.loading = false
      //         if (res.success) {
      //           this.getdata(this.formInline)
      //           this.$message({
      //             type: 'success',
      //             message: '数据保存成功！'
      //           })
      //         } else {
      //           this.$message({
      //             type: 'info',
      //             message: res.msg
      //           })
      //         }
      //       })
      //       .catch(err => {
      //         this.editFormVisible = false
      //         this.loading = false
      //         this.$message.error('保存失败，请稍后再试！')
      //       })
      //   } else {
      //     console.log("////////////////////////")
      //     return false
      //   }
      // })
      this.$confirm('确定要操作吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let obj = {
            user: this.editForm
          }
          // 修改
          userSave(obj)
            .then(res => {
              console.log("54545454546", res)
              this.userdatafetch()

              if (res.success) {
                console.log(4564564545645456456);
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('操作失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作！'
          })
        })
      this.closeDialog("edit")

    },
    // 删除用户
    deleteUser(index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let obj = { id: row.id }
          // 删除
          userDelete(obj)
            .then(res => {
              console.log(res)
              if (res.success) {
                this.$message({
                  type: 'success',
                  message: '数据已删除!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('数据删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除！'
          })
        })
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.title = '修改用户'
        this.editForm.id = row.id
        this.editForm.username = row.username
        this.editForm.nickname = row.nickname
        this.editForm.phone = row.phone
        this.editForm.role = row.role
        this.editForm.status = row.status
        this.editForm.registerDate = row.registerDate
        this.editForm.profile = row.profile
        this.editForm.agreement = row.agreement
        this.editForm.birthday = row.birthday
        this.editForm.idcard = row.idcard
        this.editForm.fillname = row.fillname
        this.editForm.sex = row.sex
      } else {
        this.title = '添加用户'
        this.editForm.id = ''
        this.editForm.username = ''
        this.editForm.nickname = ''
        this.editForm.phone = ''
        this.editForm.role = ''
        this.editForm.status = ''
        this.editForm.registerDate = ''
        this.editForm.profile = ''
        this.editForm.agreement = ''
        this.editForm.birthday = ''
        this.editForm.idcard = ''
        this.editForm.fillname = ''
        this.editForm.sex = ''
      }
    },
    // 选中菜单
    changemenu(arr) {
      let change = []
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].checked) {
          change.push(arr[i].id)
        }
      }
      return change
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage
      this.formInline.limit = parm.pageSize
      this.getdata(this.formInline)
    },
    //搜索事件
    search() {
      console.log(this.formInlinew)
      let arr = []
      store.state.userDatatoo.map((item) => {
        if (item.username.includes(this.formInlinew.username)
          || item.phone.includes(this.formInlinew.phone)) {
          arr.push(item)
        }
      })
      // console.log(arr)
      this.userData = arr
      // this.getdata(this.formInline)
    },
    // 选择复选框事件
    selectChange(val) {
      this.selectdata = val
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == 'edit') {
        this.editFormVisible = false
      } else if (dialog == 'perm') {
        this.dataAccessshow = false
      } else if (dialog == 'unit') {
        this.unitAccessshow = false
      }
    },
    checkPhoneNumber() {
      const phoneReg = /^1[3456789]\d{9}$/
      console.log("--------------", this)
      if (!phoneReg.test(this.phoneNumber)) {

      }
    },
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
  text-align: right;
}

.userRole {
  width: 100%;
}
</style>

